package com.arui.springsecuritystudy.service.impl;

import com.arui.springsecuritystudy.dto.UserDTO;
import com.arui.springsecuritystudy.security.LoginUser;
import com.arui.springsecuritystudy.service.LoginService;
import com.arui.springsecuritystudy.utils.JwtUtil;
import com.arui.springsecuritystudy.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @Description TODO
 * @Date 2024/4/3 15:12
 * @Created by 10574
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;

    @Override
    public String login(UserDTO userDTO) throws Exception {
        final String username = userDTO.getUsername();
        final String password = userDTO.getPassword();
        if (!StringUtils.hasText(username)) {
            throw new Exception("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new Exception("密码不能为空");
        }
        final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        final Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new Exception("用户名或者密码错误");
        }
        // 使用userId生成token
        final LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        final String userId = String.valueOf(loginUser.getUser().getId());
        redisCache.setCacheObject("login:" + userId, loginUser);
        return JwtUtil.createJWT(userId);
    }

    @Override
    public void logout() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisCache.deleteObject("login:" + loginUser.getUser().getId());
    }
}
